/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import cn.hutool.core.io.FileUtil;
import com.yami.shop.bean.app.dto.IndexImgDto;
import com.yami.shop.bean.model.Ercode;
import com.yami.shop.bean.model.IndexImg;
import com.yami.shop.service.ErcodeService;
import com.yami.shop.service.IndexImgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@Api(tags = "首页轮播图接口")
public class ErcodeController {


    @Autowired
    private ErcodeService ercodeService;

    @Value("${app.uploadPath}")
    public String filepath;

    /**
     * 首页轮播图接口
     */
    @GetMapping("/ercode/{title}")
    @ApiOperation(value = "根据标题获取二维码图片", notes = "根据标题获取二维码图片")
    public ResponseEntity<InputStreamResource> ercodeImg(@PathVariable String title) throws IOException {


        Ercode ercode = ercodeService.getByTitle(title);

        if(ercode==null){
            return ResponseEntity.notFound().build();
        }

        String filename = ercode.getImgUrl();
        String extName = FileUtil.extName(filename);
        HttpHeaders headers =  new HttpHeaders();
        String contentType = "image/"+extName;
        headers.set("Cache-Control","max-age=36000");


        FileSystemResource file = new FileSystemResource(filepath+'/'+filename);

        if(file.exists()){
            return ResponseEntity.ok().headers(headers).contentLength(file.contentLength())
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(new InputStreamResource(file.getInputStream()));
        }else{
            return ResponseEntity.notFound().build();
        }
    }


}
